const crypto = require('crypto');

// 加密
function genSign(src, key, iv) {
    let sign = '';
    const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    sign += cipher.update(src, 'utf8', 'hex');
    sign += cipher.final('hex');
    return sign;
}

// 解密
function deSign(sign, key, iv) {
    let src = '';
    const cipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    src += cipher.update(sign, 'hex', 'utf8');
    src += cipher.final('utf8');
    return src;
}

// ase-128-cbc 加密算法要求key和iv长度都为16
const key = Buffer.from('Limslution2218..', 'utf8');
const iv = Buffer.from('Limslution9413..', 'utf8');

function aesEncrypt(plainText){
	return genSign(plainText, key, iv);
}

function aesDecrypt(encrypted) {
	return deSign(encrypted, key, iv);
}

function aesDecryptByKey(encrypted,keyText) {
    const theKey = Buffer.from(keyText, 'utf8');
    return deSign(encrypted, theKey, iv);
}

function md5(plainText){
	var hash = crypto.createHash('md5');
	hash.update(plainText);
	return hash.digest('hex')
}

function md5WithSalt(plainText){
	const salt="lims_v5";
	var hash = crypto.createHash('md5');
	hash.update(plainText+salt);
	return hash.digest('hex')
}


module.exports = {
    genSign, //AES加密，要输入加密用的key，iv
    deSign,  //AES解密，要输入加密用的key，iv
    aesEncrypt, //用内置的密码AES加密
    aesDecrypt, //用内置的密码AES解密
    md5WithSalt, //用内置的盐MD5
    aesDecryptByKey, //AES解密，要输入加密用的key，不输入iv
    md5
};

//使用样例

// // 加密
//
// const encrypted = aesEncrypt('hello world');
// console.log(encrypted); // 764a669609b0c9b041faeec0d572fd7a
//
//
// // 解密
//
// const decrypted=aesDecrypt(encrypted);
// console.log(decrypted); // hello world
//
//
// //md5
// const md5text=md5WithSalt("hello");
// console.log(md5text);